package com.example.study.ipc

import android.os.Binder
import android.os.IBinder
import android.os.Parcel

/**
 * Created by lijinxi on 2024/2/28
 * @Description:
 */
abstract class BookManagerStub : Binder(), IBookManager {
    companion object {
        private const val DESCRIPTOR = "com.example.study.ipc.IBookManager"
        const val TRANSAVTION_getBooks = FIRST_CALL_TRANSACTION
        const val TRANSAVTION_addBook = FIRST_CALL_TRANSACTION + 1

        fun asInterface(binder: IBinder?): IBookManager? {
            if (binder == null) return null
            val iin = binder.queryLocalInterface(DESCRIPTOR)
            if (iin != null && iin is IBookManager) {
                return iin
            }
            return BookManagerProxy(binder)
        }
    }

    init {
        attachInterface(this, DESCRIPTOR)
    }

    override fun asBinder(): IBinder {
        return this
    }

    override fun onTransact(code: Int, data: Parcel, reply: Parcel?, flags: Int): Boolean {
        when (code) {
            INTERFACE_TRANSACTION -> {
                reply?.writeString(DESCRIPTOR)
                return true
            }

            TRANSAVTION_getBooks -> {
                data.enforceInterface(DESCRIPTOR)
                val result = getBooks()
                reply?.writeNoException()
                reply?.writeTypedList(result)
                return true
            }

            TRANSAVTION_addBook -> {
                data.enforceInterface(DESCRIPTOR)
                var arg0: Book? = null
                if (data.readInt() != 0) {
                    arg0 = Book.createFromParcel(data)
                }
                addBook(arg0)
                reply?.writeNoException()
                return true
            }
        }
        return super.onTransact(code, data, reply, flags)
    }
}